package logic

import (
	"box-mart-api/cache"
	"box-mart-api/moder"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"box-mart-api/boxrpc/boxrpc"
	"box-mart-api/boxrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsShowLogic {
	return &GoodsShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsShowLogic) GoodsShow(in *boxrpc.GoodsShowRequest) (*boxrpc.GoodsShowResponse, error) {
	// todo: add your logic here and delete this line

	var goods moder.Goods

	key := fmt.Sprintf("goodsId_%d", in.GoodsId)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		err := goods.GoodsShow(moder.DB, in.GoodsId)
		if err != nil {
			return nil, errors.New("商品不存在")
		}
		marshal, _ := json.Marshal(goods)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &goods)
	}
	err := goods.GoodsShow(moder.DB, in.GoodsId)
	if err != nil {
		return nil, err
	}
	return &boxrpc.GoodsShowResponse{
		Title:   goods.Title,
		Price:   goods.Price,
		GoodsId: int64(goods.ID),
	}, nil
}
